//
//  OAuthViewController.swift
//  WeiBo test
//
//  Created by Aquarius_wing on 16/5/5.
//  Copyright © 2016年 Wing. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
    
    let webView=UIWebView()
    override func loadView() {
        webView.delegate=self
        view=webView
    }
    
    //MARK: 监听方法
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    @objc private func fullAccount(){
        let jsString="document.getElementById('userId').value='15002730134',document.getElementById('passwd').value='lwy1995211';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupUI()
        
        //加载网页
        loadOauthPage()
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    private func loadOauthPage(){
        let urlString="https://api.weibo.com/oauth2/authorize?"+"client_id="+client_id+"&redirect_uri="+redirect_uri
        let url=NSURL(string: urlString)
        let request=NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }

    private func setupUI(){
        self.navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: #selector(OAuthViewController.close))
        self.navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: #selector(OAuthViewController.fullAccount))
    }

}

//专门处理 webView所有的协议方法
extension OAuthViewController:UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //如果返回BOOL,一般表示,如果为true 表示当前对象可以正常工作,否则就不能
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlString=request.URL?.absoluteString else{
            return false
        }
        //这个时候urlString一定有值
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        if !urlString.hasPrefix(redirect_uri){
            return false
        }
        
        //程序走到这里,urlString一定是redirect_uri
        guard let query=request.URL?.query else{
            return false
        }
        //获取用户令牌
        let codStr="code="
        let code=query.substringFromIndex(codStr.endIndex)
        UserAccountViewModel().loadAccessToken(code) { (error) in
            print("error",error)
            self.dismissViewControllerAnimated(true, completion: {
                //跳到欢迎页
                NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerNotification, object: self)
            })
        }
        return false
    }
    
    //把关于账户的网络获取包在了UserAccountViewModel中
    
}